'use strict';

const { Controller } = require('egg');

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    ctx.validate({
      id: { type: 'string' },
      password: { type: 'string' },
    }, ctx.request.query);
    const { id, password } = ctx.request.query;
    const result = await ctx.model.User.findByPk(Number(id));
    if (result) {
      if (result.password === password) {
        ctx.status = 204;
      } else {
        ctx.status = 401;
      }
    } else {
      ctx.status = 404;
    }
  }

  async signup() {
    const { ctx } = this;
    ctx.validate({
      name: { type: 'string', max: 29 },
      password: { type: 'string', max: 99 },
    }, ctx.request.query);
    const { name, password } = ctx.request.query;
    const user = await ctx.model.User.create({ name, password });
    if (user) {
      ctx.status = 201;
      ctx.body = user;
    } else {
      ctx.throw(500, 'ctx.model.User.create() return nothing');
    }
  }
}

module.exports = UserController;
